import { useState } from "react";
import axios from "axios";
import { calculateBazi, analyzeBaziWithMarriage } from "./baziUtis";

// 定义生成八字分析的函数
function generateBaziAnalysis(date, time, gender) {
    const bazi = calculateBazi(date, time);
    if (!bazi) throw new Error("八字计算失败，请检查输入日期是否有效");
    const analysis = analyzeBaziWithMarriage(bazi, gender);
    return { bazi: `${bazi.year} ${bazi.month} ${bazi.day} ${bazi.hour}`, analysis };
}

function BaziForm() {
    // 定义状态变量
    const [name, setName] = useState("");
    const [gender, setGender] = useState("male");
    const [birthDate, setBirthDate] = useState("");
    const [birthTime, setBirthTime] = useState("");
    const [result, setResult] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");

    // 处理表单提交事件
    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError("");
        setResult(null);

        try {
            // 检查必填字段
            if (!name || !gender || !birthDate || !birthTime) {
                throw new Error("请填写完整的姓名、性别、出生日期和时辰");
            }

            // 验证出生日期格式
            const dateObj = new Date(birthDate);
            if (isNaN(dateObj.getTime())) {
                throw new Error("出生日期格式不正确，请选择有效日期");
            }

            // 验证出生时辰格式
            const [hour, minute] = birthTime.split(":").map(Number);
            if (isNaN(hour) || isNaN(minute) || hour < 0 || hour > 23 || minute < 0 || minute > 59) {
                throw new Error("出生时辰格式不正确，请使用 HH:MM 格式（例如 12:30）");
            }

            // 生成八字分析
            const analysis = generateBaziAnalysis(birthDate, birthTime, gender);
            if (!analysis.bazi) {
                throw new Error("八字计算失败，请检查输入是否正确或尝试其他日期");
            }

            // 更新结果状态
            setResult({
                ...analysis,
                name,
                gender,
                showMarriageDetail: false,
                marriageLoading: false,
                marriageResult: null
            });
        } catch (err) {
            // 捕获错误并设置错误信息
            setError(err.message);
        } finally {
            // 无论成功与否，都停止加载状态
            setLoading(false);
        }
    };

    // 处理姻缘分析请求
    const handleMarriageAnalysis = async () => {
        setResult(prev => ({...prev, marriageLoading: true }));
        try {
            // 准备请求数据
            const requestData = {
                name,
                gender,
                birthDate,
                birthTime,
                bazi: result.bazi
            };
            console.log('Sending marriage analysis request:', requestData);
            // 发送 POST 请求
            const response = await axios.post('http://localhost:5000/api/marriage', requestData);
            // 更新结果状态
            setResult(prev => ({
                ...prev,
                marriageLoading: false,
                marriageResult: response.data.answer,
                showMarriageDetail: true
            }));
        } catch (err) {
            // 捕获错误并更新结果状态
            console.error('姻缘分析请求失败:', err);
            setResult(prev => ({
                ...prev,
                marriageLoading: false,
                marriageResult: "姻缘分析获取失败，请稍后再试"
            }));
        }
    };

    // 解析姻缘分析结果的文本格式
    function parseMarriageAnswer(text) {
        // 处理标题（### **标题**）
        text = text.replace(/### \*\*(.*?)\*\*/g, '<h3 style="color: #1890ff; border-bottom: 2px solid #e0e0e0; padding-bottom: 8px; margin-top: 25px;">$1</h3>');
        // 处理加粗（**内容**）
        text = text.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #333; font-weight: 600;">$1</strong>');
        // 处理列表项（- 内容 或 -- 子列表）
        text = text.replace(/^(\s*)- (.*)/gm, (match, indent, content) => {
            const level = indent.length / 2;
            const listStyle = level === 0? 'list-style: disc;' : 'list-style: circle; padding-left: 30px;';
            return `<li style="${listStyle}">${content}</li>`;
        });
        // 处理段落（空行转换为 <br> 或段落分隔）
        text = text.replace(/\n{2,}/g, '</p><p>');
        text = text.replace(/^\s*/gm, '');
        return `<p>${text}</p>`;
    }

    return (
        <div className="App" style={{ padding: "20px", minHeight: "100vh", display: "flex", flexDirection: "column" }}>
            <h1 style={{ textAlign: "center", margin: "30px 0", fontSize: "24px", fontWeight: "600" }}>专业八字命理分析</h1>

            <form onSubmit={handleSubmit} style={{ flex: 1, display: "flex", flexDirection: "column", gap: "15px" }}>
                <div style={{ display: "flex", flexDirection: "column", gap: "5px" }}>
                    <label style={{ fontSize: "16px", fontWeight: "500" }}>姓名：</label>
                    <input
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        required
                        style={{ padding: "10px", borderRadius: "8px", border: "1px solid #e0e0e0", fontSize: "16px" }}
                    />
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: "5px" }}>
                    <label style={{ fontSize: "16px", fontWeight: "500" }}>性别：</label>
                    <select
                        value={gender}
                        onChange={(e) => setGender(e.target.value)}
                        style={{ padding: "10px", borderRadius: "8px", border: "1px solid #e0e0e0", fontSize: "16px" }}
                    >
                        <option value="male">男</option>
                        <option value="female">女</option>
                    </select>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: "5px" }}>
                    <label style={{ fontSize: "16px", fontWeight: "500" }}>出生日期：</label>
                    <input
                        type="date"
                        value={birthDate}
                        onChange={(e) => setBirthDate(e.target.value)}
                        required
                        style={{ padding: "10px", borderRadius: "8px", border: "1px solid #e0e0e0", fontSize: "16px" }}
                    />
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: "5px" }}>
                    <label style={{ fontSize: "16px", fontWeight: "500" }}>出生时辰：</label>
                    <input
                        type="time"
                        value={birthTime}
                        onChange={(e) => setBirthTime(e.target.value)}
                        required
                        style={{ padding: "10px", borderRadius: "8px", border: "1px solid #e0e0e0", fontSize: "16px" }}
                    />
                </div>

                <button
                    type="submit"
                    disabled={loading}
                    style={{
                        padding: "12px",
                        borderRadius: "8px",
                        border: "none",
                        backgroundColor: "#1890ff",
                        color: "white",
                        fontSize: "18px",
                        fontWeight: "600",
                        cursor: "pointer",
                        opacity: loading? 0.6 : 1
                    }}
                >
                    {loading? "计算中..." : "立即生成八字排盘"}
                </button>

                {error && <span style={{ color: "red", fontSize: "16px", marginTop: "10px", alignSelf: "flex-start" }}>{error}</span>}
            </form>

            {result && (
                <div style={{ marginTop: "30px", padding: "20px", backgroundColor: "#f5f5f5", borderRadius: "12px" }}>
                    <h2 style={{ textAlign: "center", marginBottom: "20px", fontSize: "20px", fontWeight: "600" }}>八字命理分析报告</h2>
                    <div style={{ fontSize: "18px", marginBottom: "15px", fontWeight: "500", textAlign: "center" }}>
                        {result.gender === "male"?"先生" : "女士"} {result.name} 的八字：{result.bazi}
                    </div>

                    <table style={{ width: "100%", borderCollapse: "collapse", marginTop: "10px" }}>
                        <thead>
                            <tr style={{ backgroundColor: "#f0f0f0" }}>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>分析项目</th>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>分析内容</th>
                            </tr>
                        </thead>
                        <tbody>
                            {result.analysis.map((item, index) => (
                                <tr key={index} style={{ borderBottom: "1px solid #e0e0e0" }}>
                                    <td style={{ padding: "12px", fontSize: "16px", fontWeight: "500" }}>{item.title}</td>
                                    <td style={{ padding: "12px", fontSize: "16px" }}>{item.content}</td>
                                </tr>
                            ))}
                            {result.analysis.find(item => item.title === "一生姻缘情况") && (
                                <tr style={{ borderBottom: "1px solid #e0e0e0" }}>
                                    <td style={{ padding: "12px", fontSize: "16px", fontWeight: "500" }}>姻缘详情</td>
                                    <td style={{ padding: "12px", fontSize: "16px" }}>
                                        <button
                                            onClick={handleMarriageAnalysis}
                                            style={{
                                                padding: "8px 16px",
                                                backgroundColor: "#ff4d4f",
                                                color: "white",
                                                border: "none",
                                                borderRadius: "4px",
                                                cursor: "pointer"
                                            }}
                                        >
                                            {result.marriageLoading? "分析中..." : "查看详情"}
                                        </button>
                                        {result.showMarriageDetail && (
                                            <div style={{ marginTop: "10px", padding: "10px", backgroundColor: "#fff9f9", borderRadius: "4px" }}
                                                dangerouslySetInnerHTML={{
                                                    __html: parseMarriageAnswer(result.marriageResult)
                                                }}/>
                                        )}
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}

export default BaziForm;    